package com.hmdp.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;


@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryTypeList() {
        //opsForList写法
        String key = CACHE_SHOP_TYPE_KEY;
        //1. 从redis中查询商铺缓存
        List<String> shopTypeJson = stringRedisTemplate.opsForList().range(key, 0, -1);
        //2.有就直接返回
        if (CollectionUtil.isNotEmpty(shopTypeJson)) {
            //JSON字符串转对象 排序后返回
            List<ShopType> shopTypes = JSONUtil.toList(shopTypeJson.toString(), ShopType.class);
            Collections.sort(shopTypes, (o1, o2) -> o1.getSort() - o2.getSort());
            return Result.ok(shopTypes);
        }
        //3.没有就查询数据库
        List<ShopType> shopTypes = query().orderByAsc("sort").list();
        //4.不存在，返回错误
        if (CollectionUtil.isEmpty(shopTypes)) {
            return Result.fail("店铺不存在");
        }
        //5.存在，写入redis
        List<String> shopTypesJson = shopTypes.stream()
                .map(shopType -> JSONUtil.toJsonStr(shopType))
                .collect(Collectors.toList());
        stringRedisTemplate.opsForList().rightPushAll(key, shopTypesJson);
        //6.返回ok
        return Result.ok(shopTypes);
    }
}
